package com.wangjiacai.utils.translate.baidu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangjiacai.utils.translate.Translate;
import com.wangjiacai.utils.translate.baidu.properties.BaiduProperty;
import com.wangjiacai.utils.utils.EncryptUtil;
import com.wangjiacai.utils.utils.RandomStringUtils;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

public class BaiDuTranslate implements Translate {

    private String appID;
    private String appSecret;
    private String url="https://fanyi-api.baidu.com/api/trans/vip/translate?q={1}&from={2}&to={2}&appid={3}&salt={4}&sign={5}";
    private RestTemplate restTemplate;

    public BaiDuTranslate(BaiduProperty baiduProperty) {
        this.appID = baiduProperty.getAppID();
        this.appSecret = baiduProperty.getAppSecret();
        this.restTemplate = new RestTemplate();
    }

    public BaiDuTranslate(String appID, String appSecret) {
        this.appID = appID;
        this.appSecret = appSecret;
        this.restTemplate = new RestTemplate();
    }

    @Override
    public CompletableFuture<String> translateAsync(String sourceLan, String targetLan, String content) {
        return CompletableFuture.supplyAsync(() -> this.translate(sourceLan, targetLan, content));
    }

    @Override
    public CompletableFuture<String> translateAsync(String sourceLan, String targetLan, String content, Executor executor) {
        return CompletableFuture.supplyAsync(() -> this.translate(sourceLan, targetLan, content),executor);
    }

    @Override
    public String translate(String sourceLan, String targetLan, String content) {
        String salt=RandomStringUtils.randomString(6);
        String src=appID+content+salt+appSecret;
        String sign= EncryptUtil.encodeByMD5(src);
        System.out.println("sign:"+sign);
        String response=restTemplate.getForObject(url,String.class,content,sourceLan,targetLan,appID,salt,sign);
        System.out.println(response);
        JSONArray jsonArray= JSONObject.parseObject(response).getJSONArray("trans_result");
        String result=jsonArray.getJSONObject(0).getString("dst");
        return result;
    }

}
